import {useState, memo} from 'react';
import {StyleSheet, Text, TouchableOpacity} from 'react-native';

const timerButtonClick = (
  seconds: number = 60,
  setTitle: React.Dispatch<React.SetStateAction<string>>,
  setDisabled: React.Dispatch<React.SetStateAction<boolean>>,
) => {
  setTitle(JSON.stringify(seconds) + 's');
  setDisabled(true)
  // Create a timer
  const timerId = setInterval(() => {
    if (seconds > 1) {
      seconds -= 1;
      setTitle(JSON.stringify(seconds) + 's');
    } else {
      clearInterval(timerId);
      setTitle('Verify Code');
      setDisabled(false)
    }
  }, 1000);
};

const TimerButton = memo((props: {seconds: number}) => {
  const [title, setTitle] = useState('Verify Code');
  const [disabled, setDisabled] = useState(false);
  return (
    <TouchableOpacity
      style={styles.verifyCodeButtonStyle}
      disabled={disabled}
      onPress={() => timerButtonClick(props.seconds, setTitle, setDisabled)}>
      <Text style={styles.verifyCodeTextStyle}> {title} </Text>
    </TouchableOpacity>
  );
});

const styles = StyleSheet.create({
  verifyCodeButtonStyle: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 100,
    height: 30,
    borderRadius: 5,
    backgroundColor: 'steelblue',
  },
  verifyCodeTextStyle: {
    fontSize: 14,
    fontWeight: 'bold',
    color: 'white',
  },
});

export default TimerButton;
